<template>
	<view class="map-container">
		<map id="map" style="width: 100%; height:40%;" :latitude="latitude" :longitude="longitude" scale="16"
			show-location="true" :markers="mapMakers">
		</map>
		<view class="return-view-search">
			<view class="return-view" @click="returnPreview">
				<uni-icons type="left" size="30" color="#66596b"></uni-icons>
			</view>
			<view class="search-view">
				<uni-easyinput prefixIcon="search" primaryColor="#66596b" v-model="searchAddressValue"
					placeholder="搜索地点" @confirm="searchAddress" @clear="clearSeachValue"></uni-easyinput>
			</view>
		</view>

		<!-- 周围地址列表 -->
		<view class="address-list">
			<view class="address-item" v-for="(item,index) in addressList" :key="index" @click="clickAddress(item)">
				<view class="address-content">
					<view class="icons-view">
						<uni-icons type="location" size="22"></uni-icons>
					</view>
					<view class="address-obj">
						<view class="name-pos">
							{{item.name}}
						</view>
						<view class="distance-address">
							{{item.distance}}米 | {{item.formatted_address}}
						</view>
					</view>
					<view class="checked-view">
						<uni-icons type="checkmarkempty" size="26" color="#66596b" v-show="item.isChecked"></uni-icons>
					</view>
				</view>
				<divider-line :width="100"></divider-line>
			</view>
		</view>

		<!-- 底部的确认发送按钮 -->
		<view class="bottom-btn">
			<button :class="{ 'userAble': !btnDisAble }" :disabled="!btnDisAble" type="primary"
				@click="confirmSelect">确认选择</button>
		</view>
	</view>
</template>



<script>
	import dividerLine from '@/components/common-components/DividerLine.vue';
	import eventBus from '@/common/mitt/eventBus.js'
	export default {
		name: 'MapContainer',
		components: {
			dividerLine
		},
		data() {
			return {
				btnDisAble: false,
				addressList: [{
					name: '金平大厦',
					distance: '100',
					isChecked: false,
					formatted_address: '兴业银行(金华永康支行)金同大厦'
				}], // 周围地址列表
				onLoadAddressList: [], // 页面初次加载数据时获取的周边地址列表
				searchAddressValue: '',
				latitude: '',
				longitude: '',
				mapMakers: [{
					id: 1,
					latitude: 0,
					longitude: 0,
					iconPath: '../../static/icons/marker_location.png',
				}], // 标记点
			};
		},

		onLoad() {
			// 获取经纬度
			this.getLocationFunc();
		},

		methods: {
			// 获取经纬度
			getLocationFunc() {
				const that = this;
				that.addressList = [];
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						that.latitude = res.latitude;
						that.longitude = res.longitude;
						// console.log(`纬度: ${res.latitude}, 经度: ${res.longitude}`);
						that.mapMakers = [];
						that.mapMakers.push({
							id: 1,
							latitude: that.latitude,
							longitude: that.longitude,
							iconPath: '../../static/icons/marker_location.png',
						})
						// 获取周边信息
						that.getAroundPlaceList();
					},
					fail: (err) => {
						console.error('获取位置失败', err);
						uni.showToast({
							title: '获取位置失败！请稍后再试...',
							icon: 'none'
						})
					}
				});
			},

			// 获取周边信息
			getAroundPlaceList() {
				const that = this;
				const url =
					`https://restapi.amap.com/v5/place/around?location=${that.longitude},${that.latitude}&key=9b525f4169003c38e05af3059964347d&keywords=${that.searchAddressValue}&output=json`;
				uni.request({
					url: url,
					method: 'GET',
					success: (response) => {
						if (response.statusCode === 200) {
							// console.log(response);
							const arr = response.data.pois;
							that.formatAddressList(arr);
							// 将初始数据存储到 onLoadAddressList 中
							if (that.onLoadAddressList.length === 0) {
								that.onLoadAddressList = that.addressList.slice();
							}
						} else {
							uni.showToast({
								title: '没获取到周边信息,请稍后再试...',
								icon: 'none'
							})
						}
					},
					fail: (error) => {
						uni.showToast({
							title: '没获取到周边信息,请稍后再试...',
							icon: 'none'
						})
						console.error(error);
					}
				});
			},

			formatAddressList(resultArr) {
				this.addressList = [];
				resultArr.forEach(item => {
					this.addressList.push({
						name: item.name,
						distance: item.distance,
						isChecked: false,
						formatted_address: item.pname + item.cityname + item.adname + item.address,
						location: item.location
					})
				})
			},

			returnPreview() {
				uni.navigateBack()
			},
			clickAddress(item) {
				this.addressList.forEach(ad => {
					ad.isChecked = false;
				})
				item.isChecked = true;
				this.btnDisAble = true;
			},
			confirmSelect() {
				// 携带数据返回上一页（选择的那个地址）
				let selectedAddress = null;
				this.addressList.forEach(item => {
					if (item.isChecked) {
						selectedAddress = item;
					}
				});
				if (selectedAddress) {
					eventBus.emit('selectedAddress', selectedAddress);
					uni.navigateBack();
				} else {
					uni.showToast({
						title: '请先选择一个地址',
						icon: 'none'
					});
				}
			},
			searchAddress() {
				this.btnDisAble = false;
				if (this.searchAddressValue.trim() === '') {
					uni.showToast({
						title: '请先输入关键字!',
						icon: 'none'
					})
					// 当用户清空搜索关键词时，显示初始数据
					this.onLoadAddressList.forEach(item => {
						item.isChecked = false;
					})
					this.addressList = this.onLoadAddressList.slice();
				} else {
					this.getAroundPlaceList()
				}
			},
			clearSeachValue() {
				// 当用户清空搜索关键词时，显示初始数据
				this.onLoadAddressList.forEach(item => {
					item.isChecked = false;
				})
				this.addressList = this.onLoadAddressList.slice();
				this.btnDisAble = false;
			},
		}
	};
</script>

<style lang="scss" scoped>
	.map-container {
		width: 100vw;
		height: 100vh;
		background-color: #f8f8f8;

		.return-view-search {
			margin-top: 20px;
			width: 90%;
			margin-left: auto;
			margin-right: auto;
			display: flex;
			align-items: center;

			.return-view {
				display: flex;
				width: 15%;
				text-align: left;
			}

			.search-view {
				width: 95%;
			}
		}

		.address-list {
			margin-top: 20px;
			width: 90%;
			margin-left: auto;
			margin-right: auto;
			height: 45%;
			overflow-y: scroll;
			// background-color: #b7fff3;

			.address-item {
				.address-content {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.address-obj {
						width: 80%;
						// background-color: #66596b;
						// margin-left: -40rpx;
						align-items: center;

						.name-pos {
							font-size: 35rpx;
						}

						.distance-address {
							width: 100%;
							display: flex;
							color: #8b8b8b;
							margin-top: 10rpx;
						}
					}

					.checked-view {
						width: 70rpx;
						display: flex;
						align-items: center;
						justify-content: flex-end;
						// background-color: #e3e3e3;
					}
				}
			}

		}

		.bottom-btn {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 50px;
			background-color: #fff;

			button {
				width: 90%;
				height: 50px;
				border-radius: 30px;
				background-color: #66596b;
				color: #fff;
				letter-spacing: 2px;
				font-size: 34rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.userAble {
				width: 90%;
				height: 50px;
				border-radius: 30px;
				background-color: #66596b;
				color: #fff;
				letter-spacing: 2px;
				font-size: 34rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				opacity: 0.7;
			}
		}

	}
</style>